package com.junjun.ssm.controller;

import com.alibaba.fastjson.JSON;
import com.junjun.ssm.dto.GodsDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("shopping")
@Slf4j
public class GodsController {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @PostMapping("addGods")
    public String addGods(@RequestBody GodsDto godsDto) {
        String key = "user";

        if (redisTemplate.opsForHash().get(key, godsDto.getGodsName()) == null) {

            redisTemplate.opsForHash().put(key,godsDto.getGodsName(),godsDto);
        } else {

            LinkedHashMap obj = (LinkedHashMap) redisTemplate.opsForHash().get(key,godsDto.getGodsName());
            int num = (Integer)obj.get("nums");
            obj.put("nums",num+godsDto.getNums());
            redisTemplate.opsForHash().put(key,godsDto.getGodsName(),obj);
        }



        return "ok";
    }

    @PostMapping("queryGods")
    public List<Object> queryGods() {
        String key = "user";
        List<Object> values = redisTemplate.opsForHash().values(key);



        return values;
    }
    @PostMapping("updateGods")
    public String updateGods(@RequestBody GodsDto godsDto) {
        String key = "user";



            LinkedHashMap obj = (LinkedHashMap) redisTemplate.opsForHash().get(key,godsDto.getGodsName());

            obj.put("nums",godsDto.getNums());
            redisTemplate.opsForHash().put(key,godsDto.getGodsName(),obj);
              



        return "ok";
    }
    @PostMapping("deleteGods")
    public String deleteGods(@RequestBody GodsDto godsDto) {
        String key = "user";




        redisTemplate.opsForHash().delete(key,godsDto.getGodsName());



        return "ok";
    }


}
